<template>
  <div class="goods" v-if="shopInfo.recommend">
    <div class="recomment" v-for="(item,index) in shopInfo.recommend" :key="index">
      <p>{{item.name}}</p>
      <div class="recomment-list">
        <div class="recomment-goods" v-for="(good,index) in item.items" :key="index" @click="showGoodview(good)">
          <div><img :src="good.image_path"></div>
          <div class="desc">
            <div class="name">{{good.name}}</div>
            <div class="month"><span>月售{{good.month_sales}}</span><span>好评{{good.satisfy_rate}}</span></div>
            <div class="price">
              <div style="color:#ec6206;font-size:.4rem;"> ¥{{good.activity.benefit_text}}</div>
              <CartControll :food="good" @decreaseCount="decreaseCount" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 商品列表 -->
    <div class="good-list">
      <!-- 左侧菜单 -->
      <div class="menu-left" ref="menuScroll">
        <ul>
          <li :class="{'li-active':currentIndex === index}" v-for="(item,index) in shopInfo.menu" :key="index" @click="handleLi(index)">
            <img style="width:.45rem;margin-right:.2rem" v-if="item.icon_url" :src="item.icon_url" alt="" srcset=""> {{item.name}}
          </li>
        </ul>
      </div>
      <!-- 右侧菜单 -->
      <div class="menu-right" ref="foodScroll">
        <ul>
          <li v-for="(item,index) in shopInfo.menu" :key="index" class="food-list-hook">
            <!-- 内容上 -->
            <div class="category-title">
              <strong>{{item.name}}</strong>
              <span>{{item.description}}</span>
            </div>
            <div v-for="(food,idx) in item.foods" :key="idx" class="menu-right-content" @click="showGoodview(food)">
              <div><img :src="food.image_path" alt="" srcset=""></div>
              <div class="detail-good">
                <div style="font-weight:bold;font-size:.35rem;">{{food.name}}</div>
                <div class="description">{{food.description | fontNumber}}</div>
                <div class="month"><span>月售{{food.month_sales}}</span><span>好评{{food.satisfy_rate}}</span></div>
                <div class="price-count">
                  <div style="margin-right:auto;color:#ec6206;"> ¥{{food.activity.fixed_price}}</div>
                  <CartControll :food="food" @decreaseCount="decrease" />
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <!-- 购物车 -->
    <div class="cart">
      <ShopCart :shopInfo="shopInfo" />
    </div>
    <!-- 商品详情 -->
    <div class="good-detail-obj" v-if="showGoodView">
      <FoodView :selectFood="selectFood" @close="close" />
    </div>
  </div>
</template>
<script>
import CartControll from '../../components/shops/CartControll.vue'
import BScroll from "better-scroll";
import ShopCart from './ShopCart.vue'
import FoodView from './FoodView.vue'
export default {
  name: 'goods',
  data () {
    return {
      shopInfo: {},
      liIndex: 0,
      foods: [],
      menuScroll: {},
      foodScroll: {},
      scrollY: 0,//右侧当前滚动的值
      listHeight: [],//12个区列表高度
      selectFood: null,
      showGoodView: false
    }
  },
  created () {
    this.getData()
  },
  computed: {
    //根据右侧滚动的位置，确定左侧菜单的下标
    currentIndex () {
      for (let i = 0; i < this.listHeight.length; i++) {
        let hight1 = this.listHeight[i]
        let hight2 = this.listHeight[i + 1]

        //判断是否在两个高度之间
        if (this.scrollY >= hight1 && this.scrollY < hight2) {
          return this.liIndex = i
        }
      }
      return this.liIndex = 0
    }
  },
  methods: {
    getData () {
      this.$axios('/api/profile/batch_shop').then((res) => {

        res.data.recommend.forEach(recommend => {
          recommend.items.forEach(item => {
            item.count = 0;
          });
        });

        res.data.menu.forEach(menu => {
          menu.foods.forEach(food => {
            food.count = 0;
            // console.log(food);

            this.foods.push(food)
          });

        });
        this.shopInfo = res.data
        // console.log('shopInfo',this.shopInfo);
        this.$nextTick(() => {
          // DOM已经更新
          this.initScroll();
          // 计算12个区的高度
          this.calculateHeight();
        });

      })
      this.foods = this.filterObj(this.foods)
      // console.log('this.foods',this.foods);
    },

    filterObj (objcArray) {
      for (var i = 0; i < objcArray.length; i++) {
        for (var j = i + 1; j < objcArray.length;) {
          if (objcArray[i].id== objcArray[j].id) { //通过id属性进行匹配；
            objcArray.splice(j, 1); //去除重复的对象；
          } else {
            j++;
          }
        }
      }
      return objcArray;
    },
    initScroll () {
      this.menuScroll = new BScroll(this.$refs.menuScroll, {
        click: true
      });

      this.foodScroll = new BScroll(this.$refs.foodScroll, {
        probeType: 3,
        click: true
      });
      this.foodScroll.on("scroll", pos => {
        this.scrollY = Math.abs(Math.round(pos.y));
        // console.log(this.scrollY);
      });
      this.updated()
    },
    updated () {
      //解决better-scroll因为图片没有下载完导致的滚动条高度不够，无法浏览全部内容的问题。
      //原因是better-scroll初始化是在dom加载后执行，此时图片没有下载完成，导致滚动条高度计算不准确。
      //利用图片的complete属性进行判断，当所有图片下载完成后再对scroll重新计算。
      let img = document.getElementsByClassName('menu-right')[0].getElementsByTagName('img')
      // console.log(img);
      let count = 0
      let length = img.length
      if (length) {
        let timer = setInterval(() => {
          if (count == length) {
            // console.log('refresh')
            this.foodScroll.refresh()
            clearInterval(timer)
          } else if (img[count].complete) {
            count++
          }
        }, 0)
      }

    },
    calculateHeight () {
      let foodlist = this.$refs.foodScroll.getElementsByClassName(
        "food-list-hook"
      );
      // 每个区的高度添加到数组中
      let height = 0;
      this.listHeight.push(height);

      for (let i = 0; i < foodlist.length - 1; i++) {
        let item = foodlist[i];
        // 累加
        height += item.clientHeight;
        this.listHeight.push(height);
      }
      // console.log(this.listHeight);
    },
    /* 计算数量 */
    decreaseCount (e, foodId) {
      this.shopInfo.recommend.forEach(recommend => {
        recommend.items.forEach(item => {
          if (foodId == item.item_id)
            item.count = item.count + e;
        });
      });
    },

    // 计算商品数量
    decrease (e, foodId) {
      // console.log(e, foodId);
      this.shopInfo.menu.forEach(menu => {
        menu.foods.forEach(item => {
          if (foodId == item.item_id)
            item.count = item.count + e;
        });
      });
    },
    handleLi (e) {
      this.liIndex = e
      let foodList = this.$refs.foodScroll.getElementsByClassName('food-list-hook')
      let el = foodList[e]
      this.foodScroll.scrollToElement(el, 250)
    },
    showGoodview (item) {
      // console.log(item);
      this.selectFood = item
      this.showGoodView = true
    },
    close (e) {
      this.showGoodView = e
    }
  },
  filters: {
    fontNumber (date) {
      const length = date.length
      if (length > 8) {
        var str = ''
        str = date.substring(0, 10) + '...'
        return str
      } else {
        return date
      }
    }
  },
  components: {
    CartControll,
    BScroll,
    ShopCart,
    FoodView
  }
}
</script>
<style scoped>
.goods {
  position: relative;
  height: calc(100% - 10.666667vw);
}
.recomment {
  position: relative;
  z-index: 9;
  background-color: #fff;
  /* padding: 0.25rem; */
}
.recomment p {
  padding: 0.2rem 0 0 0.2rem;
}

.recomment-list {
  display: flex;
  overflow-x: auto;
  overflow-y: hidden;
}
.desc {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  margin-top: 0.25rem;
}
.desc div {
  width: 3.5rem;
  height: 0.45rem;
}
.recomment-goods {
  padding: 0.25rem;
}
.recomment-goods img {
  margin-left: 15%;
  width: 2rem;
}
.recomment-goods .name {
  color: rgb(34, 34, 34);
  font-size: 0.3rem;
}
.recomment-goods .month,
.month {
  color: rgb(116, 113, 113);
  font-size: 0.2rem;
}
.recomment-goods .price {
  display: flex;
  font-size: 0.25rem;
  height: 0.5rem;
  line-height: 0.5rem;
}
.recomment-goods div {
  margin-right: 0.2rem;
  color: rgb(77, 79, 79);
}
.recomment-list::-webkit-scrollbar {
  display: none;
}
.good-list {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.menu-left ul li {
  display: flex;
  padding: 0.25rem 0.5rem;
  width: 2rem;
  height: 0.6rem;
  line-height: 0.5rem;
  color: rgb(41, 41, 41);
  font-size: 0.3rem;
  align-items: center;
}
.detail-good {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.li-active {
  background-color: #fff;
  color: rgb(0, 0, 0);
}
.menu-right {
  width: 100%;
  height: 100vh;
  background-color: #fff;
  overflow: hidden;
}
.menu-right img {
  width: 2rem;
}
.menu-right ul li {
  padding: 0.3rem 0 0 0.3rem;
}
.description {
  color: rgb(129, 124, 124);
  font-size: 0.25rem;
}
.price-count {
  width: 4rem;
  display: flex;
  justify-content: space-around;
  margin-top: 0.2rem;
}
.count-good {
  display: flex;
}
.detail {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.detail div {
  margin-top: 0.3rem 0;
}
.price {
  display: flex;
}
.menu-right-content {
  margin-bottom: 0.5rem;
  display: flex;
}
.category-title {
  height: 1rem;
  text-align: left;
  line-height: 1rem;
  padding-left: 0.2rem;
  font-weight: bold;
  color: rgb(83, 82, 82);
  font-size: 0.35rem;
}
.category-title strong {
  color: black;
}
.category-title span {
  font-weight: normal;
  margin-left: 0.2rem;
  font-size: 0.1rem;
}
</style>
